package org.hd.source.service;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.hd.source.entity.Source;
import org.hd.source.entity.Tag;
import org.hd.source.exception.BizException;
import org.hd.source.mapper.SourceMapper;
import org.hd.source.mapper.TagMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class TagService {

    @Autowired
    private TagMapper tagMapper;
    @Autowired
    private SourceMapper sourceMapper;

    public List<Tag> list(Integer status){
        return tagMapper.selectList(Wrappers.<Tag>lambdaQuery().eq(status != null, Tag::getStatus, status));
    }

    public void add(String tagName){
        List<Tag> exist = tagMapper.selectList(Wrappers.<Tag>lambdaQuery().eq(Tag::getName, tagName));
        if(exist.size() > 0){
            throw new BizException("标签名已存在!");
        }
        Tag tag = new Tag();
        tag.setName(tagName);
        tagMapper.insert(tag);
    }

    public void update(String tagId, String tagName){
        List<Tag> exist = tagMapper.selectList(Wrappers.<Tag>lambdaQuery().eq(Tag::getName, tagName));
        if(exist.size() > 0){
            throw new BizException("标签名已存在!");
        }
        Tag tag = new Tag();
        tag.setId(tagId);
        tag.setName(tagName);
        tagMapper.updateById(tag);
    }

    public void delete(String tagId){
        List<Source> exists = sourceMapper.selectList(Wrappers.<Source>lambdaQuery()
                .like(Source::getTagIds, tagId));
        if(exists.size() > 0){
            throw new BizException("存在资源使用了该标签！");
        }

        tagMapper.deleteById(tagId);
    }

    public void updateStatus(String tagId, Integer status) {
        Tag tag = new Tag();
        tag.setId(tagId);
        tag.setStatus(status);
        tagMapper.updateById(tag);
    }
}
